<?php
namespace app\job;

use think\facade\Queue;
use think\facade\Db;
use think\exception\ValidateException;
use think\queue\Job;

class JobMembersTotal
{
    // 课程学习明细
    public function task1(Job $job, array $data)
    {

        $isJobDone = $this->doRecordJobTask1($data);

        if ($isJobDone['code'] == 0) {

            $job->delete();

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassName = 'app\job\JobMembersTotal@task1';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName = "MembersTotalJobQueue";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $isJobDone['ts'], 'download_id' => $isJobDone['download_id'], 'page' => $isJobDone['page'], 'start' => $isJobDone['start'], 'end' => $isJobDone['end']];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        } elseif($isJobDone['code'] == 1) {
            $job->delete();
            Db::name('document')->where('id', '=', $data['download_id'])->update(['url' => '/csv/total/MembersRecord-'.date('YmdHis', $data['ts']).'.csv', 'complete_time'=>time()]);
            Db::name('temporary_members')->where('type', '=', 'MembersTotalJobQueue')->delete();
        } else {
            if ($job->attempts() > 3){
                $job->delete();
            }

        }

    }


    /**
     * 根据消息中的数据进行实际的业务处理...
     * @param array $data
     * @return bool
     */
    protected function doRecordJobTask1(array $data)
    {
        $date = date('YmdHis', $data['ts']);
        $file_path = root_path() . "/public/csv/total/MembersRecord-".$date.".csv";


        if (!file_exists($file_path)) {
            $fp = fopen($file_path,'a');

            //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));

            //添加导出标题
            fputcsv($fp, ['工号', '姓名', 'Division', '部门', 'Moments(S)', 'Offline Session(S)', 'E-Learning(S)', '轻学堂(S)', '直播课(S)', '总学习时长(S)']);
        } else {
            $fp = fopen($file_path,'a');

            //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        }
        $time = [];
        $time1 = [];
        $time[] = ['add_time', 'between', [strtotime($data['start']), strtotime($data['end'])+86399]];
        $time1[] = ['date', '>=', date('Ymd', strtotime($data['start']))];
        $time1[] = ['date', '<=', date('Ymd', strtotime($data['end']))];
        //+moments学习时间
        $subQuery1 = Db::table('o_study_log')
            ->where('type', '=', 1)
            ->where($time)
            ->field('SUM(time) as moments, userid')
            ->group('userid')
            ->buildSql();

        //+learnnow学习时长
        $subQuery2 = Db::table('o_classes_log')
            ->where($time)
            ->field('SUM(learning_time) as learnnow, userid')
            ->group('userid')
            ->buildSql();

        //+elearning学习时长
        $subQuery3 = Db::table('o_learning_log')
            ->where($time)
            ->field('SUM(learning_time) as learning, userid')
            ->group('userid')
            ->buildSql();

        //+直播课学习时长
        $subQuery4 = Db::table('o_live_log')
            ->where($time1)
            ->field('SUM(time) as live, userid')
            ->group('userid')
            ->buildSql();

        $members = Db::name('temporary_members')
            ->alias('a')
            ->join($subQuery1.'b','a.userid=b.userid','left')
            ->join($subQuery2.'c','a.userid=c.userid','left')
            ->join($subQuery3.'d','a.userid=d.userid','left')
            ->join($subQuery4.'e','a.userid=e.userid','left')
            ->where('a.type', '=', 'MembersTotalJobQueue')
            ->field('a.members_id, a.name, a.userid, a.openid, a.department_name, a.division, b.moments, c.learnnow, d.learning, e.live')
            ->order('id', 'asc')
            ->page($data['page'], 5)
            ->select()
            ->toArray();

        if ($members) {
            foreach($members as &$v) {
                $inf = $v;

                $count = mb_strlen($inf['userid']);
                if ($count == 6) {
                    if (is_numeric($inf['userid'])) {
                        $userid = "'00".$inf['userid'];
                    } else {
                        $userid = $inf['userid'];
                    }
                } else {
                    $userid = $inf['userid'];
                }

                if (empty($inf['moments'])) {
                    $moments = 0;
                } else {
                    $moments = $inf['moments'];
                }

                if (empty($inf['learnnow'])) {
                    $learnnow = 0;
                } else {
                    $learnnow = $inf['learnnow'];
                }

                if (empty($inf['learning'])) {
                    $learning = 0;
                } else {
                    $learning = $inf['learning'];
                }
                if (empty($inf['live'])) {
                    $live = 0;
                } else {
                    $live = $inf['live'];
                }
                
                $qxt = 0;

                $qxt_time = get_stat_data_by_open_ids($v['userid'], $data['start'], $data['end']);
                if ($qxt_time['ret'] == 0) {
                    if (!empty($qxt_time['data'])) {
                        $qxt += $qxt_time['data'][0]['studyTime'];
                    }
                }



                $total = $qxt + $moments + $learnnow + $learning + $live;
                $array = [
                    $userid,
                    $inf['name'],
                    $inf['division'],
                    $inf['department_name'],
                    $moments,
                    $learnnow,
                    $learning,
                    $qxt,
                    $live,
                    $total
                ];

                fputcsv($fp, $array);
            }
            return ['code' => 0, 'ts' => $data['ts'], 'download_id' => $data['download_id'], 'page' => ($data['page'] + 1), 'start' => $data['start'], 'end' => $data['end']];

        } else {

            return ['code' => 1];
        }
    }
}